package com.yc.study.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yc.study.entity.Answer;
import com.yc.study.entity.User;
import com.yc.study.service.IAnswerService;
import com.yc.study.service.IUserService;
import com.yc.study.vo.AnswerVo;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Arrays;
import java.util.Optional;

/**
 * 前端控制器
 *
 * @author 王妍
 * @since 2022-02-20
 */
@RestController
@RequestMapping("/study/answer")
@AllArgsConstructor
public class AnswerController {

  private final IAnswerService answerService;

  private final IUserService userService;

  @PostMapping
  public void submitQuestion(Principal principal, @RequestBody Answer answer) {
    final Long studentId =
        Optional.ofNullable(userService.loadUserByUserName(principal.getName()))
            .map(User::getId)
            .orElseThrow(() -> new UsernameNotFoundException("用户名不存在！！！"));
    answer.setStudentId(studentId);
    answerService.save(answer);
  }

  /** 获取问题列表 */
  @GetMapping("/student")
  public Page<AnswerVo> getAnswerListByStudentId(
      Principal principal, Page<AnswerVo> answerVoPage, AnswerVo answerVo) {
    final Long studentId =
        Optional.ofNullable(userService.loadUserByUserName(principal.getName()))
            .map(User::getId)
            .orElseThrow(() -> new UsernameNotFoundException("用户名不存在！！！"));
    answerVo.setStudentId(studentId);
    return answerService.loadPageVoByStudentId(answerVoPage, answerVo);
  }

  @GetMapping("/teacher")
  public Page<AnswerVo> getAnswerListByTeacherId(
      Principal principal, Page<AnswerVo> answerVoPage, AnswerVo answerVo) {
    final Long teacherId =
        Optional.ofNullable(userService.loadUserByUserName(principal.getName()))
            .map(User::getId)
            .orElseThrow(() -> new UsernameNotFoundException("用户名不存在！！！"));
    answerVo.setTeacherId(teacherId);
    return answerService.loadPageVoByTeacherId(answerVoPage, answerVo);
  }

  @DeleteMapping
  public void delete(@RequestBody Long[] answerIds) {
    answerService.removeBatchByIds(Arrays.asList(answerIds));
  }
}
